//获取音频元素和按钮
const audio = document.getElementById('background-music')
const button = document.getElementById('play-pause-btn')
//初始化音频的状态
let isPlaying = false
//给按钮绑定事件
button.addEventListener('click', function() {
    if (isPlaying) {
        //如果正在播放，就暂停音乐
        audio.pause()
        //停止旋转
        button.classList.remove('rotate')
    } else {
        //如果没有播放，就开始播放
        audio.play().catch(err => {
            console.error('音乐播放失败：', err)
        })
        button.classList.add('rotate')
    }
    //切换播放的状态
    isPlaying = !isPlaying
})
// 素材:['🐏', '🌿', '🌸', '🍄', '🌼', '🎋', '🍀', '🌵', '🌻']

//初始化游戏
const palyArea = document.querySelector('.play-area')
const gridMap = {}
const symbols = ['🐏', '🌿', '🌸', '🍄', '🌼', '🎋', '🍀', '🌵', '🌻']

//创建网格布局
for (let row = 0; row < 20; row++) {
    for (let col = 0; col < 20; col++) {
        const cell = document.createElement('div')
        cell.className = 'grid-cell'
        palyArea.appendChild(cell)
        gridMap[`${col}-${row}`] = cell
    }
}
// console.log(gridMap)

//卡片管理
let tileList = [] //存储所有的卡片数组
let selectedTiles = []
const slots = document.querySelectorAll('.slot')
const countDisplay = document.getElementById('left-count')

//生成具体的卡片元素
function createTile(row, col, level) {
    const tile = document.createElement('div')
    tile.className = 'tile'
    tile.style.zIndex = 10 - level
    tile.dataset.index = `${col}-${row}` //存储卡片的坐标
    return tile
}

//检查卡片位置是否有效
// layout 当前卡片的二维数组（0空，1已有卡片)
function isValid(row, col, layout) {
    //检查四个方向是否有卡片
    return ![layout[row][col - 1],
        layout[row - 1]?.[col - 1],
        layout[row - 1]?.[col],
        layout[row - 1]?.[col + 1],
    ].includes(1)
}

//生成卡片布局
function generateLayout(level) {
    //初始化20*20的二维数组
    const layout = Array.from({
        length: 20
    }, () => Array(20).fill(0))
    //根据level确定生成范围
    for (let i = level; i < 19 - level; i++) {
        for (let j = 1; j < 10; j++) {
            // 20% 概率生成卡片，并且检查该位置是否有效 
            if (Math.random() < 0.2 && isValid(i, j, layout)) {
                layout[i][j] = 1;
                layout[i][18 - j] = 1;
            }
        }
    }
    //根据layput创建卡片并添加到DOM
    layout.forEach((row, i) => {
        row.forEach((val, j) => {
            if (val === 1) {
                const tile = createTile(i, j, level);
                gridMap[`${j}-${i}`].appendChild(tile);
                tileList.push(tile);
            }
        });
    });
}

//初始化卡片
for (let i = 7; i > 0; i--) generateLayout(i)

//更新剩余卡片的数量
function updateCount() {
    countDisplay.textContent = tileList.length
}
//移除多余的卡片，保证卡片是3的倍数
const extra = tileList.length % 3
if (extra !== 0) {
    const toRemove = tileList.splice(-extra, extra)
    toRemove.forEach(tile => tile.parentNode.removeChild(tile))
}
updateCount()

//分配图案
const patternList = []
const totalGroups = Math.floor(tileList.length / 3)
for (let i = 0; i < totalGroups; i++) {
    patternList.push(...Array(3).fill(symbols[i % symbols.length]))
}
// patternList.sort(()=>Math.random() -0.5)
shuffle(patternList)
tileList.forEach((tile, i) => {
    tile.textContent = patternList[i]
    tile.dataset.type = patternList[i]
})
//洗牌算法
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}
//给被遮住的卡片添加遮罩层
function renderOverlay() {
    document.querySelectorAll('.overlay').forEach(mask => mask.remove())
    tileList.forEach(tile => {
        const rect = tile.getBoundingClientRect()
        const points = [
            [rect.left, rect.top],
            [rect.left + 49, rect.top],
            [rect.left, rect.top + 49],
            [rect.left + 49, rect.top + 49]
        ]
        //定点是否被覆盖
        const isCovered = points.some(([x, y]) => {
            const el = document.elementFromPoint(x, y)
            return el !== tile && tileList.includes(el)
        })
        //添加遮罩层
        if (isCovered) {
            const overlay = document.createElement('div')
            overlay.className = 'overlay'
            overlay.style.zIndex = tile.style.zIndex;
            tile.parentNode.appendChild(overlay)
        }
    })
}
renderOverlay()

//游戏逻辑
palyArea.addEventListener('click', function(e) {
    if (!e.target.classList.contains("tile")) return;
    const tile = e.target;
    tile.parentNode.removeChild(tile);
    tileList = tileList.filter(t => t !== tile); 
    updateCount();

    selectedTiles.push(tile); 
    
    if(selectedTiles.length > 7) endGame()
    
    checkMatches()
    renderOverlay(); // 重新渲染遮罩层 
    updateSlots()
})

//更新选择槽中卡片的显示
function updateSlots(){
    slots.forEach(slot => slot.innerHTML = '')
    selectedTiles.forEach((tile,i) =>{
        const clone = tile.cloneNode(true)
        clone.style.position = 'static'
        slots[i].appendChild(clone)
    })
}

//积分系统
let currentScore = 0;
let bestScore = localStorage.getItem('bestScore') || 0;
const currentScoreElement = document.getElementById('current-score');
const bestScoreElement = document.getElementById('best-score');

//更新显示的分数
function updateScores() {
    currentScoreElement.textContent = currentScore;
    bestScoreElement.textContent = bestScore;
}

//初始化分数显示
updateScores();

//排行榜系统
const leaderboardList = document.getElementById('leaderboard-list');
let leaderboard = JSON.parse(localStorage.getItem('leaderboard')) || [];

//更新排行榜显示
function updateLeaderboard() {
    leaderboardList.innerHTML = '';
    leaderboard.sort((a, b) => b.score - a.score).slice(0, 10).forEach((entry, index) => {
        const li = document.createElement('li');
        li.className = 'leaderboard-item';
        li.innerHTML = `
            <span class="rank">${index + 1}</span>
            <span class="player-name">${entry.name}</span>
            <span class="player-score">${entry.score}</span>
        `;
        leaderboardList.appendChild(li);
    });
}

//初始化排行榜
updateLeaderboard();

//添加新的得分记录
function addNewScore(score) {
    const playerName = prompt('恭喜你获得了新的高分！请输入你的名字：') || '匿名玩家';
    leaderboard.push({ name: playerName, score: score });
    leaderboard.sort((a, b) => b.score - a.score);
    if (leaderboard.length > 10) {
        leaderboard = leaderboard.slice(0, 10);
    }
    localStorage.setItem('leaderboard', JSON.stringify(leaderboard));
    updateLeaderboard();
}

//检查选中卡片是否有三个相同可以消除
function checkMatches(){
    const countMap = selectedTiles.reduce((acc,tile)=>{
        acc[tile.dataset.type] = (acc[tile.dataset.type] || 0) + 1;
        return acc
    },{});
    
    Object.entries(countMap).forEach(([type,count])=>{
        if(count >= 3){
            //计算积分：每消除一组加10分，额外的卡片每个加5分
            const extraTiles = count - 3;
            const points = 10 + (extraTiles * 5);
            currentScore += points;
            
            //显示分数增加动画
            currentScoreElement.classList.add('score-increase');
            setTimeout(() => {
                currentScoreElement.classList.remove('score-increase');
            }, 500);
            
            //更新最高分
            if (currentScore > bestScore) {
                bestScore = currentScore;
                localStorage.setItem('bestScore', bestScore);
                
                //显示新纪录提示
                const newRecord = document.createElement('div');
                newRecord.className = 'new-record';
                newRecord.textContent = '新纪录！';
                document.querySelector('.score-panel').appendChild(newRecord);
                setTimeout(() => newRecord.remove(), 2000);
            }
            
            updateScores();
            selectedTiles = selectedTiles.filter(tile => tile.dataset.type !== type);
        }
    });
}

//游戏失败的处理
function endGame(){
    if (currentScore > 0) {
        addNewScore(currentScore);
    }
    alert('游戏失败，请重新开始');
    location.reload();
}

//定时检查是否通关
setInterval(()=>{
    if(tileList.length === 0 && selectedTiles.length === 0){
        //通关奖励：额外加100分
        currentScore += 100;
        updateScores();
        if (currentScore > bestScore) {
            bestScore = currentScore;
            localStorage.setItem('bestScore', bestScore);
        }
        addNewScore(currentScore);
        alert('恭喜通关！');
        location.reload();
    }
},1000)

// 游戏说明面板逻辑
const helpBtn = document.getElementById('help-btn');
const tutorialPanel = document.getElementById('tutorial-panel');
const closeTutorialBtn = document.getElementById('close-tutorial');

// 创建遮罩层
const overlay = document.createElement('div');
overlay.className = 'tutorial-overlay';
document.body.appendChild(overlay);

// 显示教程
function showTutorial() {
    tutorialPanel.classList.add('show');
    overlay.classList.add('show');
}

// 隐藏教程
function hideTutorial() {
    tutorialPanel.classList.remove('show');
    overlay.classList.remove('show');
}

// 绑定事件
helpBtn.addEventListener('click', showTutorial);
closeTutorialBtn.addEventListener('click', hideTutorial);
overlay.addEventListener('click', hideTutorial);

// 游戏开始时显示教程
window.addEventListener('load', () => {
    setTimeout(showTutorial, 500);
});
